#include "Thread.h"

#ifdef _WIN32
#include <process.h>

Thread::Thread()
{
	mRun=false;
	mHandle=INVALID_HANDLE_VALUE;
}

Thread::~Thread()
{
	if(mRun)
		stop();
}

void Thread::start()
{
	if(!mRun)
	{
		mHandle = (HANDLE)_beginthreadex(NULL,0,thread_func,this,0,NULL);
		if(mHandle!=NULL)
			mRun=true;
	}
}

void Thread::stop()
{
	if(mRun)
	{
		mRun=false;
		WaitForSingleObject(mHandle,INFINITE);
		CloseHandle(mHandle);
		mHandle=INVALID_HANDLE_VALUE;
	}
}

unsigned int __stdcall Thread::thread_func(void *p)
{
	((Thread *)p)->run();
	_endthreadex(0);
	return 0;
}

#else

Thread::Thread()
	:mThreadId(false)
{

}
void Thread::start()
{
	if(!mRun)
	{  
		mRun=true;
		pthread_create(&mThreadId,NULL,thread_func,this);
	}
}
void Thread::stop()
{
	if(mRun)
	{
		mRun=false;
		pthread_join(mThreadId,NULL);
	}
}
void *Thread::thread_func(void *p)
{
	((Thread *)p)->run();
	pthread_exit(0);
	return NULL;
}

#endif